#!/bin/bash
# date: 2022/11/24
# auth: fearless11
# desc: install thanos
# doc: https://thanos.io
# https://www.jianshu.com/p/78ae4cf8405b

# https://thanos.io/tip/thanos/quick-tutorial.md/

# sidecar: 与prometheus部署一起，上传数据到对象存储长期存储，提供query查询
# receiver: 替换sidecar，通过prometheus远程写，实现一致性哈希，支持集群部署
# store: 读取对象存储的数据提供给query查询
# query: 实现Prometheus API，将来sidecar、store提供的数据进行聚合提供查询
# ruler: 对监控数据进行评估和告警，还可以计算出新的监控数据，将这些新数据提供给 Thanos Query 查询并且/或者上传到对象存储，以供长期存储
# compact: 将对象存储中的数据进行压缩和降低采样率，加速大时间区间监控数据查询的速度

image="quay.io/thanos/thanos:v0.14.0"
conf=$(pwd)/conf
data=$(pwd)/data
prometheus_addr="http://127.0.0.1:9090"

# deployed on the same machine as prometheus
thanos_sidecar() {
  docker run -d --name thanos_sidecar_19191 \
    -m 512m \
    --net=host \
    -v ${conf}:/etc/cos \
    -v ${data}/prometheus/data:/prometheus/data \
    -v ${data}/thanos/cos:/thanos/cos \
    ${image} \
    sidecar \
    --prometheus.url="${prometheus_addr}" \
    --http-address=0.0.0.0:19191 \
    --grpc-address=0.0.0.0:19091 \
    --tsdb.path=/prometheus/data \
    --objstore.config-file=/etc/cos/thanos_sidecar.yml \
    --log.level=info
}

thanos_store() {
  docker run -d --name thanos_store_19192 \
    -m 512m \
    --net=host \
    -v ${conf}:/etc/cos \
    -v ${data}/thanos/store:/thanos/store \
    ${image} \
    store \
    --data-dir=/thanos/store \
    --objstore.config-file=/etc/cos/thanos_cos.yaml \
    --http-address=0.0.0.0:19192 \
    --grpc-address=0.0.0.0:19092
}

thanos_query() {
  docker run -d --name thanos_query_19193 \
    -m 512m \
    --net=host \
    ${image} \
    query \
    --http-address=0.0.0.0:19193 \
    --grpc-address=0.0.0.0:19093 \
    --store=127.0.0.1:19091 \
    --store=127.0.0.1:19092
}

docker_start() {
  thanos_sidecar
  thanos_store
  thanos_query
}

docker_stop() {
  docker stop thanos_sidecar_19191
  docker rm thanos_sidecar_19191

  docker stop thanos_store_19192
  docker rm thanos_store_19192

  docker stop thanos_query_19193
  docker rm thanos_query_19193
}

docker_status() {
  docker ps -a | grep -E 'thanos_sidecar_19191|thanos_store_19192|thanos_query_19193'
}

case $1 in
start)
  docker_start
  ;;
stop)
  docker_stop
  ;;
status)
  docker_status
  ;;
*)
  echo "$0 start|stop|status"
  ;;
esac
